package com.segersten.othello.service.akka.lobby.dao;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import com.segersten.othello.service.akka.lobby.DomainPlayer;
import com.segersten.othello.service.akka.lobby.Ticket;

public class InMemoryRegisteredForMatchingDao implements RegisteredForMatchingDao
{
    private Map<DomainPlayer, Ticket> registeredForMatching = new HashMap<DomainPlayer, Ticket>();

    @Override
    public void remove(DomainPlayer dp)
    {
        registeredForMatching.remove(dp);
    }

    @Override
    public List<DomainPlayer> extractPair()
    {
        if (registeredForMatching.size() >= 2) {
            //System.out.println("Match " + registeredForMatching);
            Iterator<Entry<DomainPlayer, Ticket>> iter = registeredForMatching.entrySet().iterator();
            Entry<DomainPlayer, Ticket> e1 = iter.next();
            Entry<DomainPlayer, Ticket> e2 = iter.next();
            registeredForMatching.remove(e1.getKey());
            registeredForMatching.remove(e2.getKey());
            return Arrays.asList(e1.getKey(), e2.getKey());
        } else {
            return null;
        }
    }

    @Override
    public void put(DomainPlayer dp, Ticket ticket)
    {
        registeredForMatching.put(dp, ticket);
    }

    @Override
    public Ticket get(DomainPlayer dp)
    {
        return registeredForMatching.get(dp);
    }
}
